package com.technology.education.ui.common.login

import android.os.CountDownTimer
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.technology.education.data.AppData
import com.technology.education.data.model.LoginModel
import com.technology.education.ext.toast
import com.technology.education.network.apiService
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.callback.databind.BooleanObservableField
import me.hgj.jetpackmvvm.callback.databind.IntObservableField
import me.hgj.jetpackmvvm.callback.databind.StringObservableField
import me.hgj.jetpackmvvm.ext.request
import me.hgj.jetpackmvvm.state.ResultState

/**
 *@author:create by BZY
 *Date: 2022/2/24 09
 */
class LoginViewModel : BaseViewModel() {
    val account = StringObservableField()
    val password = StringObservableField()
    val code = StringObservableField()
    val codeNotify = StringObservableField("发送验证码")
    val sendCodeEnable = BooleanObservableField(true)

    val loginResult = MutableLiveData<ResultState<LoginModel>>()

    //登录类型,0 验证码登录 1 密码登录
    val loginType = IntObservableField(0)

    fun login() {
        if (account.get().isEmpty()){
            toast("请输入您的手机号")
            return
        }
        if (loginType.get()==0&&code.get().isEmpty()){
            toast("请输入您收到的验证码")
            return
        }
        if (loginType.get()==1&&password.get().isEmpty()){
            toast("请输入您的登录密码")
            return
        }
        request({
            apiService.login(
                hashMapOf(
                    "authCode" to code.get(),
                    "mobile" to account.get(),
                    "password" to password.get(),
                    "type" to loginType.get(),
                    "rid" to AppData.PUSH_TOKEN
                )
            )
        }, loginResult, isShowDialog = true)
    }

    fun codeLogin() {
        loginType.set(0)
    }

    fun pwdLogin() {
        loginType.set(1)
    }

    fun sendCode() {
        if (account.get().isEmpty()) {
            toast("请输入手机号码")
            return
        }
        request({ apiService.sendCode(hashMapOf("mobile" to account.get())) }, success = {
            countDown()
        },error = {
            toast(it.errorMsg)
        }, isShowDialog = false)
    }

    private var timer: CountDownTimer? = null
    private fun countDown() {
        if (timer == null) {
            timer = object : CountDownTimer(60 * 1000, 1000) {
                override fun onTick(p0: Long) {
                    codeNotify.set("${p0 / 1000}s 后重试")
                    sendCodeEnable.set(false)
                }

                override fun onFinish() {
                    codeNotify.set("重新发送")
                    sendCodeEnable.set(true)
                }

            }
        }
        timer?.start()
    }
}